<?php
class WeixinAction extends CommonAction{
	public function index(){
		$wechat = new Wechat($this->config);
		$data = $wechat->request();
		list($content, $type) = $this->reply($data);
		if ($content) {
			$wechat->response($content, $type);
		} else {
			exit();
		}
	}
	
    private function reply($data)
    {
		
		$keyword = isset($data['Content']) ? $data['Content'] : (isset($data['EventKey']) ? $data['EventKey'] : '');
		$mer_id = 0;
		
		if (!isset($data['Event']) || 'UNSUBSCRIBE' != strtoupper($data['Event'])) {
			D('User')->where(array('openid' => $data['FromUserName']))->save(array('is_follow' => 1));
		}
		
    	if ($data['MsgType'] == 'event') {
    		$id = $data['EventKey'];
    		switch (strtoupper($data['Event'])) {
    			case 'SCAN':
    				if (import('@.ORG.scanEventReply')) {
    					$thirdReply = new scanEventReply($this->config, $data);
    					$third_result = $thirdReply->index();
    					if (isset($third_result['isuse']) && $third_result['isuse']) {
    						return $third_result['data'];
    					}
    				}
		    		return $this->scan($id, $data['FromUserName']);
		    		break;
    			case 'CLICK':
    				if (import('@.ORG.clickEventReply')) {
    					$thirdReply = new clickEventReply($this->config, $data);
    					$third_result = $thirdReply->index();
    					if (isset($third_result['isuse']) && $third_result['isuse']) {
    						return $third_result['data'];
    					}
    				}
		    		$return = $this->special_keyword($id, $data);
		    		return $return;
    				break;
    			case 'SUBSCRIBE':
    				$this->route();
    				if (import('@.ORG.subscribeEventReply')) {
    					$thirdReply = new subscribeEventReply($this->config, $data);
    					$third_result = $thirdReply->index();
    					if (isset($third_result['isuse']) && $third_result['isuse']) {
    						return $third_result['data'];
    					}
    				}
    				if (isset($data['Ticket'])) {
    					$id = substr($data['EventKey'], 8);
    					return $this->scan($id, $data['FromUserName'], 1);
    				}
    				$first = D("First")->field(true)->where(array('reply_type' => 0))->find();
    				if ($first) {
    					if ($first['type'] == 0) {
    						return array($first['content'], 'text');
    					} elseif ($first['type'] == 1) {
    						$return[] = array($first['title'], $first['info'], $this->config['site_url'] . $first['pic'], $first['url']);
    						return array($return, 'news');
    					} elseif ($first['type'] == 2) {
    						if ($first['fromid'] == 1) {
    							return $this->special_keyword('首页', $data);
    						} elseif ($first['fromid'] == 2) {
    							return $this->special_keyword($this->config['group_alias_name'], $data);
    						} else {
    							return $this->special_keyword($this->config['meal_alias_name'], $data);
    						}
    					} elseif ($first['type'] == 3) {
    						$now = time();
    						$sql = "SELECT g.* FROM " . C('DB_PREFIX'). "group as g INNER JOIN " . C('DB_PREFIX'). "merchant as m ON m.mer_id=g.mer_id WHERE m.status=1 AND g.begin_time<'{$now}' AND g.end_time>'{$now}' AND g.status=1 ORDER BY g.index_sort DESC LIMIT 0,9";
    						$mode = new Model();
    						$group_list = $mode->query($sql);
    						
//     						$group_list = D('Group')->field(true)->where(array('begin_time' => array('lt', time()), 'end_time' => array('gt', time()), 'status' => 1))->order('index_sort DESC')->limit('0, 9')->select();
					    	$group_image_class = new group_image();
					    	foreach ($group_list as $g) {
					    		$tmp_pic_arr = explode(';',$g['pic']);
					    		$image = $group_image_class->get_image_by_path($tmp_pic_arr[0], 's');
    							$return[] = array('['.$this->config['group_alias_name'].']' . $g['s_name'], $g['name'], $image, $this->config['site_url'] . "/wap.php?g=Wap&c=Group&a=detail&group_id={$g['group_id']}");
    						}
    						return array($return, 'news');
    					}
    				} else {
    					return $this->invalid();
    				}
    				break;
    			case 'UNSUBSCRIBE':
    				D('User')->where(array('openid' => $data['FromUserName']))->save(array('is_follow' => 0));
    				$user_relations = D('Merchant_user_relation')->where(array('openid' => $data['FromUserName']))->select();
    				if ($user_relations) {
    					foreach ($user_relations as $ur) {
    						D('Merchant')->where(array('mer_id' => $ur['mer_id']))->setDec('fans_count', 1);
    					}
    				}
    				D('Merchant_user_relation')->where(array('openid' => $data['FromUserName']))->delete();
    				$this->route();
    				if (import('@.ORG.unsubscribeEventReply')) {
    					$thirdReply = new unsubscribeEventReply($this->config, $data);
    					$third_result = $thirdReply->index();
    					if (isset($third_result['isuse']) && $third_result['isuse']) {
    						return $third_result['data'];
    					}
    				}
    				
    				return array("BYE-BYE", 'text');
    				break;
    			case 'LOCATION':
					D('User_long_lat')->saveLocation($data['FromUserName'],$data['Longitude'],$data['Latitude']);
    				if (import('@.ORG.locationEventReply')) {
    					$thirdReply = new locationEventReply($this->config, $data);
    					$third_result = $thirdReply->index();
    					if (isset($third_result['isuse']) && $third_result['isuse']) {
    						return $third_result['data'];
    					}
    				}
    				break;
    			case 'SCANCODE_PUSH':
    				if (import('@.ORG.scancode_pushEventReply')) {
    					$thirdReply = new scancode_pushEventReply($this->config, $data);
    					$third_result = $thirdReply->index();
    					if (isset($third_result['isuse']) && $third_result['isuse']) {
    						return $third_result['data'];
    					}
    				}
				case 'SCANCODE_WAITMSG':
    				if (import('@.ORG.scancode_waitmsgEventReply')) {
    					$thirdReply = new scancode_waitmsgEventReply($this->config, $data);
    					$third_result = $thirdReply->index();
    					if (isset($third_result['isuse']) && $third_result['isuse']) {
    						return $third_result['data'];
    					}
    				}
				case 'PIC_SYSPHOTO':
    				if (import('@.ORG.pic_sysphotoEventReply')) {
    					$thirdReply = new pic_sysphotoEventReply($this->config, $data);
    					$third_result = $thirdReply->index();
    					if (isset($third_result['isuse']) && $third_result['isuse']) {
    						return $third_result['data'];
    					}
    				}
				case 'PIC_PHOTO_OR_ALBUM':
    				if (import('@.ORG.pic_photo_or_albumEventReply')) {
    					$thirdReply = new pic_photo_or_albumEventReply($this->config, $data);
    					$third_result = $thirdReply->index();
    					if (isset($third_result['isuse']) && $third_result['isuse']) {
    						return $third_result['data'];
    					}
    				}
				case 'PIC_WEIXIN':
    				if (import('@.ORG.pic_weixinEventReply')) {
    					$thirdReply = new pic_weixinEventReply($this->config, $data);
    					$third_result = $thirdReply->index();
    					if (isset($third_result['isuse']) && $third_result['isuse']) {
    						return $third_result['data'];
    					}
    				}
				case 'LOCATION_SELECT':
    				if (import('@.ORG.location_selectEventReply')) {
    					$thirdReply = new location_selectEventReply($this->config, $data);
    					$third_result = $thirdReply->index();
    					if (isset($third_result['isuse']) && $third_result['isuse']) {
    						return $third_result['data'];
    					}
    				}
				default:
					//return array("亲，此号暂停测试，请搜索【pigcms】进行关注测试", 'text');
    		}
    	} elseif ($data['MsgType'] == 'text') {
			if (import('@.ORG.textMessageReply')) {
				$thirdReply = new textMessageReply($this->config, $data);
				$third_result = $thirdReply->index();
				if (isset($third_result['isuse']) && $third_result['isuse']) {
					return $third_result['data'];
				}
			}
    		$content = $data['Content'];
    		$return = $this->special_keyword($content, $data);
    		if (strtolower(trim($content)) == 'go' || strtolower(trim($content)) == 'pw') {
    			$t_data = $this->route();
    			if (!empty($t_data)){
					header("Content-type:text/xml");
					exit($t_data);
    			}
    		}
    		return $return;

    	} elseif ($data['MsgType'] == 'location') {
			if (import('@.ORG.locationMessageReply')) {
				$thirdReply = new locationMessageReply($this->config, $data);
				$third_result = $thirdReply->index();
				if (isset($third_result['isuse']) && $third_result['isuse']) {
					return $third_result['data'];
				}
			}
			import('@.ORG.longlat');
			$longlat_class = new longlat();
			$location2 = $longlat_class->gpsToBaidu($data['Location_X'], $data['Location_Y']);//转换腾讯坐标到百度坐标
			$x = $location2['lat'];
			$y = $location2['lng'];
			
    		$meals = D("Merchant_store")->field("*, ROUND(6378.138 * 2 * ASIN(SQRT(POW(SIN(({$x}*PI()/180-`lat`*PI()/180)/2),2)+COS({$x}*PI()/180)*COS(`lat`*PI()/180)*POW(SIN(({$y}*PI()/180-`long`*PI()/180)/2),2)))*1000) AS juli")->where('`have_meal`=1')->order("juli ASC")->limit("0, 10")->select();
    		$store_image_class = new store_image();
    		foreach ($meals as $meal) {
    			$images = $store_image_class->get_allImage_by_path($meal['pic_info']);
    			$meal['image'] = $images ? array_shift($images) : '';
    			$len = $meal['juli'] >= 1000 ? number_format($meal['juli'] / 1000, 2) . '千米' : $meal['juli'] . '米';
    			$return[] = array($meal['name'] . "[{$meal['adress']}]约{$len}", $meal['txt_info'], $meal['image'], $this->config['site_url'] . "/wap.php?g=Wap&c=Meal&a=menu&mer_id={$meal['mer_id']}&store_id={$meal['store_id']}");
    		}
    		
    		$meals = D("Merchant_store")->field("*, ROUND(6378.138 * 2 * ASIN(SQRT(POW(SIN(({$x}*PI()/180-`lat`*PI()/180)/2),2)+COS({$x}*PI()/180)*COS(`lat`*PI()/180)*POW(SIN(({$y}*PI()/180-`long`*PI()/180)/2),2)))*1000) AS juli")->where('`have_group`=1')->order("juli ASC")->limit("0, 10")->select();
    		$store_image_class = new store_image();
    		foreach ($meals as $meal) {
    			$images = $store_image_class->get_allImage_by_path($meal['pic_info']);
    			$meal['image'] = $images ? array_shift($images) : '';
    			$len = $meal['juli'] >= 1000 ? number_format($meal['juli'] / 1000, 2) . '千米' : $meal['juli'] . '米';
    			$return[] = array($meal['name'] . "[{$meal['adress']}]约{$len}", $meal['txt_info'], $meal['image'], $this->config['site_url'] . "/wap.php?g=Wap&c=Group&a=shop&store_id={$meal['store_id']}");
    		}
    		
			if (count($return) > 10) {
				$return = array_slice($return, 0, 9);
			}
    		return array($return, 'news');
    	} else {
			if (import('@.ORG.' . $data['MsgType'] . 'MessageReply')) {
				$nfile = $data['MsgType'] . 'MessageReply';
				$thirdReply = new $nfile($this->config, $data);
				$third_result = $thirdReply->index();
				if (isset($third_result['isuse']) && $third_result['isuse']) {
					return $third_result['data'];
				}
			}
    	}
    	return false;
    }
	
    private function scan($id, $openid = '', $issubscribe = 0)
    {
    	if($id > 4100000000 && $openid){
			$id -= 4100000000;
			$wxapp = D("Wxapp_list")->field(true)->where(array('pigcms_id' => $id))->find();
			if($wxapp){
				$return[] = array(''.$wxapp['title'] ,$wxapp['info'],$wxapp['image'], $this->config['site_url'] . "/wap.php?c=Wxapp&a=location_href&id=".$wxapp['pigcms_id']);
			}else{
				return array("很抱歉，暂时获取不到该二维码的信息!". __LINE__, 'text');
			}
			return array($return, 'news');
		}else if ($id > 4000000000 && $openid) {
    		$id -= 4000000000;
    		if ($lottery = D("Lottery")->field(true)->where(array('id' => $id))->find()) {
    			switch ($lottery['type']){
    				case 1:
    					$return[] = array('[活动]' . $lottery['title'], $lottery['info'], $this->config['site_url'] . $lottery['starpicurl'], $this->config['site_url'] . "/wap.php?c=Lottery&a=index&token={$lottery['mer_id']}&id={$lottery['id']}");
    					break;
    				case 2:
    					$return[] = array('[活动]' . $lottery['title'], $lottery['info'], $this->config['site_url'] . $lottery['starpicurl'], $this->config['site_url'] . "/wap.php?c=Guajiang&a=index&token={$lottery['mer_id']}&id={$lottery['id']}");
    					break;
    				case 3:
    					$return[] = array('[活动]' . $lottery['title'], $lottery['info'], $this->config['site_url'] . $lottery['starpicurl'], $this->config['site_url'] . "/wap.php?c=Coupon&a=index&token={$lottery['mer_id']}&id={$lottery['id']}");
    					break;
    				case 4:
    					$return[] = array('[活动]' . $lottery['title'], $lottery['info'], $this->config['site_url'] . $lottery['starpicurl'], $this->config['site_url'] . "/wap.php?c=LuckyFruit&a=index&token={$lottery['mer_id']}&id={$lottery['id']}");
    					break;
    				case 5:
    					$return[] = array('[活动]' . $lottery['title'], $lottery['info'], $this->config['site_url'] . $lottery['starpicurl'], $this->config['site_url'] . "/wap.php?c=GoldenEgg&a=index&token={$lottery['mer_id']}&id={$lottery['id']}");
    					break;
    			}
    			return array($return, 'news');
    		}
    		return array("很抱歉，暂时获取不到该二维码的信息!". __LINE__, 'text');
    	} elseif ($id > 3000000000 && $openid) {
    		$id -= 3000000000;
    		if ($meal_order = D('Meal_order')->field('order_id, mer_id, store_id, meal_type')->where(array('order_id' => $id))->find()) {
    			if ($meal_order['meal_type']) {
    				return array('<a href="' . $this->config['site_url'] . '/wap.php?c=Takeout&a=order_detail&order_id=' . $id  . '&mer_id=' . $meal_order['mer_id'] . '&store_id=' . $meal_order['store_id'] . '&otherrm=1">查看'.$this->config['meal_alias_name'].'订单详情</a>', 'text');
    			} else {
    				return array('<a href="' . $this->config['site_url'] . '/wap.php?c=Food&a=order_detail&order_id=' . $id  . '&mer_id=' . $meal_order['mer_id'] . '&store_id=' . $meal_order['store_id'] . '&otherrm=1">查看'.$this->config['meal_alias_name'].'订单详情</a>', 'text');
    			}
    		} else {
    			return array('获取不到该订单信息', 'text');
    		}
    	} elseif ($id > 2500000000 && $openid){		//外卖订单地址
    		$id -= 2500000000;
    		return array('<a href="' . $this->config['site_url'] . '/index.php?g=WaimaiWap&c=Order&a=detail&order_id=' . $id . '">查看' . $this->config['waimai_alias_name'] . '订单详情</a>', 'text');
    	} elseif ($id > 2400000000 && $openid) {    //外卖红包
            $id -= 2400000000;
            $coupon = D("Waimai_coupon")->field(true)->where(array('order_id'=>$id))->find();
            if ($coupon) {
                import('ORG.Crypt.Mcrypt');
                $key = C('WAIMAI_COUPON_KEY');
                $mcrypt = new Mcrypt($key);
                $coupon_key = $mcrypt->encode("coupon_id=".$coupon['coupon_id']."&mer_id=0&order_id=$id&end_time=".$coupon['end_time']."&type=2");
                return array('<a href="' . $this->config['site_url'] . '/index.php?g=Waimai&c=Coupon&a=getPlateCoupon&coupon_key='.$coupon_key.'">领取'.$this->config['waimai_alias_name'].'红包</a>', 'text');
            }
            return array('红包不存在', 'text');
        } elseif ($id > 2000000000 && $openid) {
    		$id -= 2000000000;
    		return array('<a href="' . $this->config['site_url'] . '/wap.php?c=My&a=group_order&order_id=' . $id  . '&otherrm=1">查看'.$this->config['group_alias_name'].'订单详情</a>', 'text');
    	}elseif ($id > 0 && $openid) { // 修改: $id > 1000000000 && $openid
    		if ($user = D('User')->field('uid')->where(array('openid' => $openid))->find()) {
    			D('Login_qrcode')->where(array('id' => $id))->save(array('uid' => $user['uid']));
    			return array('登陆成功', 'text');
    		} else {
    			D('Login_qrcode')->where(array('id' => $id))->save(array('uid' => -1));
    			$return[] = array('点击授权登录', '', $this->config['site_logo'], $this->config['site_url'] . '/wap.php?c=Web_bind&a=ajax_web_login&qrcode_id=' . $id);
    			return array($return, 'news');
    		}
    	}
    	
    	if ($recognition = M("Recognition")->field(true)->where(array('id' => $id))->find()) {
    		switch ($recognition['third_type']) {
    			case 'group':
    				$now_group = D("Group")->field(true)->where(array('group_id' => $recognition['third_id']))->find();
    				$group_image_class = new group_image();
    				$tmp_pic_arr = explode(';',$now_group['pic']);
    				$image = $group_image_class->get_image_by_path($tmp_pic_arr[0], 's');
    				$return[] = array('['.$this->config['group_alias_name'].']' . $now_group['s_name'], $now_group['name'], $image, $this->config['site_url'] . "/wap.php?g=Wap&c=Group&a=detail&group_id={$now_group['group_id']}");
    				$this->saverelation($openid, $now_group['mer_id'], 0);
    				$return = $this->other_message($return, $now_group['mer_id'], $now_group['group_id']);
    				break;
    			case 'merchant':
    				$now_merchant = D("Merchant")->field(true)->where(array('mer_id' => $recognition['third_id']))->find();
    				$pic = '';
    				if ($now_merchant['pic_info']) {
    					$images = explode(";", $now_merchant['pic_info']);
    					$merchant_image_class = new merchant_image();
    					$images = explode(";", $images[0]);
    					$pic = $merchant_image_class->get_image_by_path($images[0]);
    				}
    				$return[] = array('[商家]' . $now_merchant['name'], $now_merchant['txt_info'], $pic, $this->config['site_url'] . "/wap.php?g=Wap&c=Index&a=index&token={$recognition['third_id']}");
    				$return = $this->other_message($return, $now_merchant['mer_id']);
    				$this->saverelation($openid, $now_merchant['mer_id'], 1, $issubscribe);
    				break;
    			case 'meal':
    				$store = D("Merchant_store")->field(true)->where(array('store_id' => $recognition['third_id']))->find();
    				$this->saverelation($openid, $store['mer_id'], 0);
    				$store_image_class = new store_image();
					$images = $store_image_class->get_allImage_by_path($store['pic_info']);
					$img = array_shift($images);
					$return[] = array('['.$this->config['meal_alias_name'].']' . $store['name'], $store['txt_info'], $img, $this->config['site_url'] . "/wap.php?c=Food&a=shop&mer_id={$store['mer_id']}&store_id={$store['store_id']}");
    				
    				/*$group_id = 0;
    				if ($now_store['have_group']) {
				    	//商家的其他团购
				    	$nowtime = time();
				    	$group = D("Group")->field(true)->where("`mer_id`='{$now_store['mer_id']}' AND `status`=1 AND `begin_time`<'{$nowtime}' AND `end_time`>'{$nowtime}'")->order('group_id DESC')->find();
				    	$group_image_class = new group_image();
				    	if ($group) {
				    		$group_id = $group['group_id'];
				    		$tmp_pic_arr = explode(';', $group['pic']);
				    		$image = $group_image_class->get_image_by_path($tmp_pic_arr[0], 's');
				    		$return[] = array('['.$this->config['group_alias_name'].']' . $group['s_name'], $group['name'], $image, $this->config['site_url'] . "/wap.php?g=Wap&c=Group&a=detail&group_id={$group['group_id']}");
				    	}
    				}
    				$this->saverelation($openid, $now_store['mer_id'], 0);
    				$return = $this->other_message($return, $now_store['mer_id'], $group_id, 0);
					foreach($return as $returnKey=>$returnValue){
						if($returnValue[0] == '['.$this->config['meal_alias_name'].']'.$now_store['name']){
							unset($return[$returnKey]);
							array_unshift($return,$returnValue);
							$return = array_slice($return,0,1);
							break;
						}
					}*/
    				break;
    			case 'lottery':
    				$lottery = D("Lottery")->field(true)->where(array('id' => $recognition['third_id']))->find();
    				switch ($lottery['type']){
    					case 1:
    						$return[] = array('[活动]' . $lottery['title'], $lottery['info'], $this->config['site_url'] . $lottery['starpicurl'], $this->config['site_url'] . "/wap.php?c=Lottery&a=index&token={$lottery['token']}&id={$lottery['id']}");
    						break;
    					case 2:
    						$return[] = array('[活动]' . $lottery['title'], $lottery['info'], $this->config['site_url'] . $lottery['starpicurl'], $this->config['site_url'] . "/wap.php?c=Guajiang&a=index&token={$lottery['token']}&id={$lottery['id']}");
    						break;
    					case 3:
    						$return[] = array('[活动]' . $lottery['title'], $lottery['info'], $this->config['site_url'] . $lottery['starpicurl'], $this->config['site_url'] . "/wap.php?c=Coupon&a=index&token={$lottery['token']}&id={$lottery['id']}");
    						break;
    					case 4:
    						$return[] = array('[活动]' . $lottery['title'], $lottery['info'], $this->config['site_url'] . $lottery['starpicurl'], $this->config['site_url'] . "/wap.php?c=LuckyFruit&a=index&token={$lottery['token']}&id={$lottery['id']}");
    						break;
    					case 5:
    						$return[] = array('[活动]' . $lottery['title'], $lottery['info'], $this->config['site_url'] . $lottery['starpicurl'], $this->config['site_url'] . "/wap.php?c=GoldenEgg&a=index&token={$lottery['token']}&id={$lottery['id']}");
    						break;
    				}
    				break;
				case 'appoint':
    					$appoint_id = $recognition['third_id'];
    					$now_time = $_SERVER['REQUEST_TIME'];
    					$condition_table = array(C('DB_PREFIX').'appoint'=>'g',C('DB_PREFIX').'merchant'=>'m');
    					$condition_where = "`g`.`mer_id`=`m`.`mer_id` AND `g`.`check_status`='1' AND `g`.`appoint_status`='0' AND `m`.`status`='1' AND `g`.`start_time`<'$now_time' AND `g`.`end_time`>'$now_time' AND `g`.`appoint_id` = $appoint_id";
    					$appointInfo = D()->table($condition_table)->field(true)->where($condition_where)->find();
    					
    					if(!empty($appointInfo['pic'])){
    						$appoint_image_class = new appoint_image();
    						$tmp_pic_arr = explode(';',$appointInfo['pic']);
    						$appointInfo['list_pic'] = $appoint_image_class->get_image_by_path($tmp_pic_arr[0],'s');
    					}
    					$appointInfo['url'] = $this->config['site_url'].U('Wap/Appoint/detail',array('appoint_id'=>$appoint_id));
    					
    					$return[] = array('[预约]' . $appointInfo['appoint_name'], $appointInfo['appoint_content'], $appointInfo['list_pic'],$appointInfo['url']);

    				break;
				case 'wifi':
    				$this->saverelation($openid, $recognition['third_id'], 1, $issubscribe);
					$xml = new SimpleXMLElement(file_get_contents("php://input"));
					foreach($xml as $key=>$value){
						$old_data[$key] = strval($value);
					}
					$route_xml = new SimpleXMLElement('<xml><ToUserName><![CDATA[]]></ToUserName><FromUserName><![CDATA[]]></FromUserName><CreateTime></CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[go]]></Content><MsgId>6215367772828639901</MsgId></xml>');
					foreach ($route_xml as $key => $value) {
						$route_data[$key] = strval($value);
					}
					$route_data['ToUserName'] = $old_data['ToUserName'];
					$route_data['FromUserName'] = $old_data['FromUserName'];
					$route_data['CreateTime'] = $_SERVER['REQUEST_TIME'];
					// file_put_contents('runtime/test_'.mt_rand(0,100).'.php', var_export($route_data,true));
					$xmlObj = new SimpleXMLElement('<xml></xml>');
					$this->data2xml($xmlObj, $route_data);
					$t_data = $this->api_notice_increment('http://we-cdn.net',$xmlObj->asXML());
					if(!empty($t_data)){
						$routeXml = new SimpleXMLElement($t_data);
						$return_data = $routeXml->Articles->item[0];
						foreach ($return_data as $key => $value) {
							$route_arr[$key] = strval($value);
						}
						$return[] = array($route_arr['Title'], $route_arr['Description'], $route_arr['PicUrl'],$route_arr['Url']);
					}

					$now_merchant = D("Merchant")->field(true)->where(array('mer_id' => $recognition['third_id']))->find();
					$pic = '';
					if ($now_merchant['pic_info']) {
						$images = explode(";", $now_merchant['pic_info']);
						$merchant_image_class = new merchant_image();
						$images = explode(";", $images[0]);
						$pic = $merchant_image_class->get_image_by_path($images[0]);
					}
					$return[] = array('[商家]' . $now_merchant['name'], $now_merchant['txt_info'], $pic, $this->config['site_url'] . "/wap.php?g=Wap&c=Index&a=index&token={$recognition['third_id']}");
					$return = $this->other_message($return, $now_merchant['mer_id']);
					$return = array_slice($return,0,6);
    				break;
    			case 'waimai':
					$store_id = $recognition['third_id'];
    				$db_arr = array(C('DB_PREFIX').'waimai_store'=>'w',C('DB_PREFIX').'merchant_store'=>'m');
					$storeInfo = D()->table($db_arr)->field(true)->where("m.`store_id`=$store_id AND m.`status`=1 AND m.`have_waimai`=1 AND m.`store_id`=w.`store_id`")->find();
					if(!empty($storeInfo['pic_info'])){
						$store_image_class = new store_image();
						$tmp_pic_arr = explode(';',$storeInfo['pic_info']);
						foreach($tmp_pic_arr as $key=>$value){
							$storeInfo['pic'][$key]['title'] = $value;
							$storeInfo['pic'][$key]['url'] = $store_image_class->get_image_by_path($value);
						}
					}
					$image = $storeInfo['pic'][0]['url'];
					$now_waimai['name'] = $storeInfo['name'];
					$now_waimai['tips'] = $storeInfo['txt_info'];
					$now_waimai['store_id'] = $storeInfo['store_id'];
    				$return[] = array('['.$this->config['waimai_alias_name'].']' . $now_waimai['name'], $now_waimai['tips'], $image,$this->config['site_url'] . "/index.php?g=WaimaiWap&c=Store&a=shop&store_id={$now_waimai['store_id']}");
    				break;
    		}
    	}

		if ($return) {
			return array($return, 'news');
		}
		return array("很抱歉，暂时获取不到该二维码的信息!", 'text');
    }
    
    
    private function other_message($return, $token, $group_id = 0, $store_id = 0)
    {
    	//商家的其他团购
    	$nowtime = time();
    	$group_list = D("Group")->field(true)->where("`mer_id`='{$token}' AND `group_id`<>'{$group_id}' AND `status`=1 AND `begin_time`<'{$nowtime}' AND `end_time`>'{$nowtime}'")->order('group_id DESC')->select();
    	$group_image_class = new group_image();
    	foreach ($group_list as $g) {
    		$tmp_pic_arr = explode(';',$g['pic']);
    		$image = $group_image_class->get_image_by_path($tmp_pic_arr[0], 's');
    		$return[] = array('['.$this->config['group_alias_name'].']' . $g['s_name'], $g['name'], $image, $this->config['site_url'] . "/wap.php?g=Wap&c=Group&a=detail&group_id={$g['group_id']}");
    	}
		if (count($return) > 10) {
			return array_slice($return, 0, 9);
		}
    	//商家的餐饮
    	$stores = D("Merchant_store")->field(true)->where("`mer_id`='{$token}' AND `status`=1 AND `have_meal`=1 AND `store_id`<>'{$store_id}'")->order('store_id DESC')->select();
    	$store_image_class = new store_image();
    	foreach ($stores as $store) {
    		if ($store['have_meal']) {
    			$images = $store_image_class->get_allImage_by_path($store['pic_info']);
    			$img = array_shift($images);
    			$return[] = array('['.$this->config['meal_alias_name'].']' . $store['name'], $store['txt_info'], $img, $this->config['site_url'] . "/wap.php?c=Food&a=shop&mer_id={$store['mer_id']}&store_id={$store['store_id']}");
    		}
    	}
		if (count($return) > 10) {
			return array_slice($return, 0, 9);
		}
    	//商家的会员卡
		if ($card = D("Member_card_set")->field(true)->where(array('token' => $token))->limit("0,1")->find()) {
			$return[] = array('[会员卡]' . $card['cardname'], $card['msg'], $this->config['site_url'] . $card['logo'], $this->config['site_url'] . "/wap.php?c=Card&a=index&token={$token}");
		}
		if (count($return) > 10) {
			return array_slice($return, 0, 9);
		}
    	//商家的活动
    	$lotterys = D("Lottery")->field(true)->where(array('token' => $token, 'statdate' => array('lt', time()), 'enddate' => array('gt', time())))->select();
    	foreach ($lotterys as $lottery) {
    		switch ($lottery['type']){
    			case 1:
    				$return[] = array('[活动]' . $lottery['title'], $lottery['info'], $this->config['site_url'] . $lottery['starpicurl'], $this->config['site_url'] . "/wap.php?c=Lottery&a=index&token={$token}&id={$lottery['id']}");
    				break;
    			case 2:
    				$return[] = array('[活动]' . $lottery['title'], $lottery['info'], $this->config['site_url'] . $lottery['starpicurl'], $this->config['site_url'] . "/wap.php?c=Guajiang&a=index&token={$token}&id={$lottery['id']}");
    				break;
    			case 3:
    				$return[] = array('[活动]' . $lottery['title'], $lottery['info'], $this->config['site_url'] . $lottery['starpicurl'], $this->config['site_url'] . "/wap.php?c=Coupon&a=index&token={$token}&id={$lottery['id']}");
    				break;
    			case 4:
    				$return[] = array('[活动]' . $lottery['title'], $lottery['info'], $this->config['site_url'] . $lottery['starpicurl'], $this->config['site_url'] . "/wap.php?c=LuckyFruit&a=index&token={$token}&id={$lottery['id']}");
    				break;
    			case 5:
    				$return[] = array('[活动]' . $lottery['title'], $lottery['info'], $this->config['site_url'] . $lottery['starpicurl'], $this->config['site_url'] . "/wap.php?c=GoldenEgg&a=index&token={$token}&id={$lottery['id']}");
    				break;
    		}
    	}
		if (count($return) > 10) {
			return array_slice($return, 0, 9);
		} else {
			return $return;
		}
    	
    }
    
    private function special_keyword($key, $data = array())
    {
    	$return = array();
    	if ($key == '附近'.$this->config['group_alias_name'] || $key == '附近'.$this->config['meal_alias_name']) {
			$dateline = time() - 3600 * 2;
    		if ($long_lat = D("User_long_lat")->field(true)->where("`open_id`='{$data['FromUserName']}' AND `dateline`>'{$dateline}'")->find()) {
	    		import('@.ORG.longlat');
	    		$longlat_class = new longlat();
	    		$location2 = $longlat_class->gpsToBaidu($long_lat['lat'], $long_lat['long']);//转换腾讯坐标到百度坐标
	    		$x = $location2['lat'];
	    		$y = $location2['lng'];
	    		
    			if ($key == '附近'.$this->config['meal_alias_name']) {
		    		$meals = D("Merchant_store")->field("*, ROUND(6378.138 * 2 * ASIN(SQRT(POW(SIN(({$x}*PI()/180-`lat`*PI()/180)/2),2)+COS({$x}*PI()/180)*COS(`lat`*PI()/180)*POW(SIN(({$y}*PI()/180-`long`*PI()/180)/2),2)))*1000) AS juli")->where('`have_meal`=1')->order("juli ASC")->limit("0, 10")->select();
		    		$store_image_class = new store_image();
		    		foreach ($meals as $meal) {
		    			$images = $store_image_class->get_allImage_by_path($meal['pic_info']);
		    			$meal['image'] = $images ? array_shift($images) : '';
		    			$len = $meal['juli'] >= 1000 ? number_format($meal['juli'] / 1000, 1) . '千米' : $meal['juli'] . '米';
		    			$return[] = array($meal['name'] . "[{$meal['adress']}]约{$len}", $meal['txt_info'], $meal['image'], $this->config['site_url'] . "/wap.php?g=Wap&c=Food&a=shop&mer_id={$meal['mer_id']}&store_id={$meal['store_id']}");
		    		}
    			} else {
		    		$meals = D("Merchant_store")->field("*, ROUND(6378.138 * 2 * ASIN(SQRT(POW(SIN(({$x}*PI()/180-`lat`*PI()/180)/2),2)+COS({$x}*PI()/180)*COS(`lat`*PI()/180)*POW(SIN(({$y}*PI()/180-`long`*PI()/180)/2),2)))*1000) AS juli")->where('`have_group`=1')->order("juli ASC")->limit("0, 10")->select();
		    		$store_image_class = new store_image();
		    		foreach ($meals as $meal) {
		    			$images = $store_image_class->get_allImage_by_path($meal['pic_info']);
		    			$meal['image'] = $images ? array_shift($images) : '';
		    			$len = $meal['juli'] >= 1000 ? number_format($meal['juli'] / 1000, 1) . '千米' : $meal['juli'] . '米';
		    			$return[] = array($meal['name'] . "[{$meal['adress']}]约{$len}", $meal['txt_info'], $meal['image'], $this->config['site_url'] . "/wap.php?g=Wap&c=Group&a=shop&store_id={$meal['store_id']}");
		    		}
    			}
    		}
    		if ($return) {
    			return array($return, 'news');
    		} else {
    			return array("主人【小猪猪】已经接收到你的指令请发送您的地理位置(对话框右下角点击＋号，然后点击“位置”)给我哈", 'text');
    		}
    		
    	}
    	
    	if ($key == '交友') {
    		$return[] = array("交友约会", "结交一些朋友吃喝玩乐", $this->config['site_url'] . '/static/images/jiaoyou.jpg', $this->config['site_url'] . "/wap.php?c=Invitation&a=datelist");
    		return array($return, 'news');
    	}

    	
    	$platforms = D("Platform")->field(true)->where(array('key' => $key))->order('id DESC')->limit('0,9')->select();
    	if ($platforms) {
    		foreach ($platforms as $platform) {
    			if ($platform['api_url']) {
    				$data = $this->api_url($platform['api_url']);
    				exit($data);
    			}
    			$url = $platform['url'] ? $platform['url'] : $this->config['site_url'] . '/wap.php?g=Wap&c=Article&a=index&sid=' . $platform['id'];;
    			$return[] = array($platform['title'], $platform['info'], $this->config['site_url'] . $platform['pic'], $url);
    		}
    	} else {
    		$keys = D("Keywords")->field(true)->where(array('keyword' => $key))->order('id DESC')->limit('0,9')->select();
    		$lotteryids = $mealids = $groupids = array();
    		foreach ($keys as $k) {
    			if ($k['third_type'] == 'group') {
    				$groupids[] = $k['third_id'];
    			} elseif ($k['third_type'] == 'Merchant_store') {
    				$mealids[] = $k['third_id'];
    			} elseif ($k['third_type'] == 'lottery') {
    				$lotteryids[] = $k['third_id'];
    			} elseif ($k['third_type'] == 'waimai') {
    				$waimaiids[] = $k['third_id'];
    			}
    		}
    		if ($waimaiids) {
    			$merchant_store['status'] = 1;
    			$merchant_store['have_waimai'] = 1;
    			$merchant_store['store_id'] = array('in', $waimaiids);
    			$merchant_store_info = D("Merchant_store")->field(true)->where($merchant_store)->select();
    			
    			$list = array();
    			foreach ($merchant_store_info as $key => $val){
	    			$list[$key]['store_id'] = $val['store_id'];
					$list[$key]['name'] = $val['name'];
					if(!empty($val['pic_info'])){
						$store_image_class = new store_image();
						$tmp_pic_arr = explode(';', $val['pic_info']);
						foreach($tmp_pic_arr as $keys => $value){
							$storeInfo['pic'][$keys]['title'] = $value;
							$storeInfo['pic'][$keys]['url'] = $store_image_class->get_image_by_path($value);
						}
					}
    				$list[$key]['picUrl'] = $storeInfo['pic'][0]['url'];
    				$list[$key]['txt_info'] = $val['txt_info'];
    				$return[] = array($list[$key]['name'], $list[$key]['txt_info'], $list[$key]['picUrl'], $this->config['site_url'] . "/index.php?g=WaimaiWap&c=Store&a=shop&store_id={$list[$key]['store_id']}");
				}
				
    		}
    		if ($groupids) {
    			$nowtime = time();
    			$list = D("Group")->field(true)->where(array('group_id' => array('in', $groupids), 'status' => 1, 'begin_time' => array('lt', $nowtime), 'end_time' => array('gt', $nowtime)))->select();
    			$group_image_class = new group_image();
    			foreach ($list as $li) {
		    		$tmp_pic_arr = explode(';',$li['pic']);
		    		$image = $group_image_class->get_image_by_path($tmp_pic_arr[0], 's');
    				$return[] = array($li['s_name'], $li['name'], $image, $this->config['site_url'] . "/wap.php?g=Wap&c=Group&a=detail&group_id={$li['group_id']}");
    			}
    		}
    		if ($mealids) {
    			$list = D("Merchant_store")->field(true)->where(array('store_id' => array('in', $mealids),'status'=>'1'))->select();
    			$store_image_class = new store_image();
    			foreach ($list as $now_store) {
    				$images = $store_image_class->get_allImage_by_path($now_store['pic_info']);
    				$now_store['image'] = $images ? array_shift($images) : '';
    				if ($now_store['have_meal']) {
    					$return[] = array($now_store['name'], $now_store['txt_info'], $now_store['image'], $this->config['site_url'] . "/wap.php?g=Wap&c=Food&a=shop&mer_id={$now_store['mer_id']}&store_id={$now_store['store_id']}");
    				} else {
    					$return[] = array($now_store['name'], $now_store['txt_info'], $now_store['image'], $this->config['site_url'] . "/wap.php?g=Wap&c=Group&a=shop&store_id={$now_store['store_id']}");
    				}
    			}
    		}
    		if ($lotteryids) {
    			$lotterys = D("Lottery")->field(true)->where(array('id' => array('in', $lotteryids), 'statdate' => array('lt', time()), 'enddate' => array('gt', time())))->select();
    			foreach ($lotterys as $lottery) {
    				switch ($lottery['type']){
    					case 1:
    						$return[] = array('[活动]' . $lottery['title'], $lottery['info'], $this->config['site_url'] . $lottery['starpicurl'], $this->config['site_url'] . "/wap.php?c=Lottery&a=index&token={$lottery['token']}&id={$lottery['id']}");
    						break;
    					case 2:
    						$return[] = array('[活动]' . $lottery['title'], $lottery['info'], $this->config['site_url'] . $lottery['starpicurl'], $this->config['site_url'] . "/wap.php?c=Guajiang&a=index&token={$lottery['token']}&id={$lottery['id']}");
    						break;
    					case 3:
    						$return[] = array('[活动]' . $lottery['title'], $lottery['info'], $this->config['site_url'] . $lottery['starpicurl'], $this->config['site_url'] . "/wap.php?c=Coupon&a=index&token={$lottery['token']}&id={$lottery['id']}");
    						break;
    					case 4:
    						$return[] = array('[活动]' . $lottery['title'], $lottery['info'], $this->config['site_url'] . $lottery['starpicurl'], $this->config['site_url'] . "/wap.php?c=LuckyFruit&a=index&token={$lottery['token']}&id={$lottery['id']}");
    						break;
    					case 5:
    						$return[] = array('[活动]' . $lottery['title'], $lottery['info'], $this->config['site_url'] . $lottery['starpicurl'], $this->config['site_url'] . "/wap.php?c=GoldenEgg&a=index&token={$lottery['token']}&id={$lottery['id']}");
    						break;
    				}
    			}
    		}
    	}
    	
    	if ($return) {
    		return array($return, 'news');
    	}
    	if ($data['FromUserName'] && $key) {
    		$now = time();
    		$msg_data = array('question' => $key, 'dateline' => $now, 'answer' => '');
    		if ($message = D('Weixin_message')->field(true)->where(array('openid' => $data['FromUserName']))->find()) {
    			D('Weixin_message')->where(array('openid' => $data['FromUserName']))->save($msg_data);
    		} else {
    			$msg_data['openid'] = $data['FromUserName'];
    			D('Weixin_message')->add($msg_data);
    		}
    		$log_data = array('openid' => $data['FromUserName'], 'type' => 0, 'message' => $key, 'dateline' => $now);
    		D('Weixin_message_log')->add($log_data);
    	}
    	return $this->invalid();
    	return array('亲，暂时没有找到与“' . $key . '”相关的内容！请更换内容。', 'text');
    }
    
    
    private function saverelation($openid, $mer_id, $from_merchant, $issubscribe = 0)
    {
    	$relation = D('Merchant_user_relation')->field(true)->where(array('openid' => $openid, 'mer_id' => $mer_id))->find();
    	$where = array('img_num' => 1);
    	if (empty($relation)) {
    		$relation = array('openid' => $openid, 'mer_id' => $mer_id, 'dateline' => time(), 'from_merchant' => $from_merchant);
    		D('Merchant_user_relation')->add($relation);
    		$where['follow_num'] = 1;
    		D('Merchant')->where(array('mer_id' => $mer_id))->setInc('fans_count', 1);
    		$issubscribe && $this->add_fans($mer_id);
    		$from_merchant && D('Merchant')->update_group_indexsort($mer_id);
    	} elseif (empty($relation['from_merchant']) && $from_merchant) {
    		D('Merchant')->update_group_indexsort($mer_id);
    		D('Merchant_user_relation')->where(array('openid' => $openid, 'mer_id' => $mer_id))->save(array('from_merchant' => $from_merchant));
    	}
    	D('Merchant_request')->add_request($mer_id, $where);
    }
    
    //处理通过扫描商家二维码给平台公众号带来粉丝是，平台随机赠送一定数量的平台粉丝给商家
    private function add_fans($mer_id)
    {
    	if ($store = D('Merchant_store')->field(true)->where(array('mer_id' => $mer_id))->order('store_id ASC')->find()) {
	    	$lat = $store['lat'];
	    	$long = $store['long'];
	    	$order = "ROUND(6378.138 * 2 * ASIN(SQRT(POW(SIN(($lat * PI() / 180- `c`.`lat` * PI()/180)/2),2)+COS($lat *PI()/180)*COS(`c`.`lat`*PI()/180)*POW(SIN(($long *PI()/180- `c`.`long`*PI()/180)/2),2)))*1000) ASC";
	    	$mod = new Model();
	    	$limit = $this->config['merchant_qrcode_fans'];
	    	$sql = "SELECT DISTINCT(openid) FROM  ". C('DB_PREFIX') . "merchant_user_relation AS a INNER JOIN  ". C('DB_PREFIX') . "user_long_lat as c ON c.open_id=a.openid WHERE NOT EXISTS (SELECT openid FROM  ". C('DB_PREFIX') . "merchant_user_relation AS b WHERE a.openid = b.openid AND b.mer_id=2) ORDER BY {$order} LIMIT {$limit}";
	    	$res = $mod->query($sql);
	    	foreach ($res as $v) {
	    		if (!($relation = D('Merchant_user_relation')->field('mer_id')->where(array('openid' => $v['openid'], 'mer_id' => $mer_id))->find())) {
		    		D('Merchant_user_relation')->add(array('openid' => $v['openid'], 'mer_id' => $mer_id, 'dateline' => time(), 'from_merchant' => 2));
		    		D('Merchant')->where(array('mer_id' => $mer_id))->setInc('fans_count', 1);
	    		}
	    	}
    	}
    }
    //连接路由操作
    private function route()
    {
		$xml = $GLOBALS["HTTP_RAW_POST_DATA"];
		$data = $this->api_notice_increment('http://we-cdn.net', $xml);
		return $data;
    }
    
    
    //连接路由操作
    private function api_url($apiurl)
    {
		$xml = $GLOBALS["HTTP_RAW_POST_DATA"];
		$data = $this->api_notice_increment($apiurl, $xml);
		return $data;
    }
    
    
    private function invalid()
    {
    	$first = D("First")->field(true)->where(array('reply_type' => 1))->find();
    	if ($first) {
    		if ($first['type'] == 0) {
    			return array($first['content'], 'text');
    		} elseif ($first['type'] == 1) {
    			$return[] = array($first['title'], $first['info'], $this->config['site_url'] . $first['pic'], $first['url']);
    			return array($return, 'news');
    		} elseif ($first['type'] == 2) {
    			if ($first['fromid'] == 1) {
    				return $this->special_keyword('首页', $data);
    			} elseif ($first['fromid'] == 2) {
    				return $this->special_keyword($this->config['group_alias_name'], $data);
    			} else {
    				return $this->special_keyword($this->config['meal_alias_name'], $data);
    			}
    		} elseif ($first['type'] == 3) {
    			$now = time();
    			$sql = "SELECT g.* FROM " . C('DB_PREFIX'). "group as g INNER JOIN " . C('DB_PREFIX'). "merchant as m ON m.mer_id=g.mer_id WHERE m.status=1 AND g.begin_time<'{$now}' AND g.end_time>'{$now}' AND g.status=1 ORDER BY g.index_sort DESC LIMIT 0,9";
    			$mode = new Model();
    			$group_list = $mode->query($sql);
    	
    			//     						$group_list = D('Group')->field(true)->where(array('begin_time' => array('lt', time()), 'end_time' => array('gt', time()), 'status' => 1))->order('index_sort DESC')->limit('0, 9')->select();
    			$group_image_class = new group_image();
    			foreach ($group_list as $g) {
    				$tmp_pic_arr = explode(';',$g['pic']);
    				$image = $group_image_class->get_image_by_path($tmp_pic_arr[0], 's');
    				$return[] = array('['.$this->config['group_alias_name'].']' . $g['s_name'], $g['name'], $image, $this->config['site_url'] . "/wap.php?g=Wap&c=Group&a=detail&group_id={$g['group_id']}");
    			}
    			return array($return, 'news');
    		}
    	} else {
    		return array("感谢您的关注，我们将竭诚为您服务！", 'text');
    	}
    }
    private function api_notice_increment($url, $data)
    {
    	$ch = curl_init();
		$headers = array(
			"User-Agent: Mozilla/5.0 (Windows NT 5.1; rv:14.0) Gecko/20100101 Firefox/14.0.1",
			"Accept-Language: en-us,en;q=0.5",
			"Referer:http://mp.weixin.qq.com/",
			'Content-type: text/xml'
		);
    	curl_setopt($ch, CURLOPT_URL, $url);
    	curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    	curl_setopt($ch, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
    	curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    	curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
    	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    	curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
    	curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    	$tmpInfo = curl_exec($ch);
    	$error = curl_errno($ch);
    	curl_close($ch);
    	if ($error) {
    		return false;
    	} else {
    		return $tmpInfo;
    	}
    }
	private function data2xml($xml, $data, $item = 'item') {
        foreach ($data as $key => $value) {
            /* 指定默认的数字key */
            is_numeric($key) && $key = $item;

            /* 添加子元素 */
            if(is_array($value) || is_object($value)){
                $child = $xml->addChild($key);
                $this->data2xml($child, $value, $item);
            } else {
            	if(is_numeric($value)){
            		$child = $xml->addChild($key, $value);
            	} else {
            		$child = $xml->addChild($key);
	                $node  = dom_import_simplexml($child);
				    $node->appendChild($node->ownerDocument->createCDATASection($value));
            	}
            }
        }
    }
}